﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using System.IO;

namespace PersonalAlbum
{
    public class ErrorHandlerAttribute : FilterAttribute, IExceptionFilter
    {
        //for some reason the original HandleError attribute did not pass the request to the Error page
        //some I just cloned it...
        public void OnException(ExceptionContext filterContext)
        {
            Controller controller = filterContext.Controller as Controller;
            if (controller == null || filterContext.ExceptionHandled)
                return;

            Exception exception = filterContext.Exception;
            if (exception == null)
                return;

            // Action method exceptions will be wrapped in a
            // TargetInvocationException since they're invoked using 
            // reflection, so we have to unwrap it.
            if (exception is TargetInvocationException)
                exception = exception.InnerException;
            try
            {
                WebLogger.LogError(exception, "url:" + filterContext.HttpContext.Request.RawUrl);
            }
            catch { }
            if (filterContext.Controller.ViewData == null)
            {
                //yes, it's ugly, but this shouldn't happen...
                StringWriter sw=new StringWriter();
                HttpContext.Current.Server.Execute("~/Views/Shared/ErrorPage.aspx", sw, false);
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
                return;
            }
            else
            {
                filterContext.Result = new ViewResult()
                {
                    TempData = controller.TempData,
                    ViewName ="Error",
                    ViewData = filterContext.Controller.ViewData
                };
            }
           
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 404;
        }
    }
}
